import time
import threading
import pyautogui
from pynput import mouse, keyboard
from pynput.keyboard import Key, KeyCode
import ctypes
from ctypes import wintypes
import tkinter as tk
from tkinter import ttk, messagebox

# 禁用pyautogui的安全特性
pyautogui.FAILSAFE = False

# Windows API
user32 = ctypes.windll.user32
MOUSEEVENTF_MOVE = 0x0001

def mouse_event(dx, dy):
    """模拟鼠标移动"""
    user32.mouse_event(MOUSEEVENTF_MOVE, dx, dy, 0, 0)

class RecoilControlApp:
    def __init__(self, root):
        self.root = root
        self.root.title("鼠标压枪助手")
        self.root.geometry("400x320")
        self.root.resizable(False, False)
        self.root.wm_attributes("-topmost", True)  # 窗口置顶
        
        # 程序状态
        self.running = False
        self.pressing_fire = False
        
        # 参数设置
        self.distance = 10          # 每次下压的像素距离
        self.interval = 0.03        # 下压间隔(秒)
        self.distance_step = 1      # 距离调整步长
        
        # 创建界面
        self.create_widgets()
        
        # 启动监听器
        self.start_listeners()
    
    def create_widgets(self):
        # 主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 距离设置
        ttk.Label(main_frame, text="下压距离 (像素):").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.distance_var = tk.StringVar(value=str(self.distance))
        distance_entry = ttk.Entry(main_frame, textvariable=self.distance_var, width=10)
        distance_entry.grid(row=0, column=1, sticky=tk.W, pady=5)
        
        # 间隔设置
        ttk.Label(main_frame, text="下压间隔 (毫秒):").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.interval_var = tk.StringVar(value=str(int(self.interval * 1000)))
        interval_entry = ttk.Entry(main_frame, textvariable=self.interval_var, width=10)
        interval_entry.grid(row=1, column=1, sticky=tk.W, pady=5)
        
        # 快捷键预设提示
        ttk.Label(main_frame, text="快捷键预设:").grid(row=2, column=0, columnspan=2, pady=5, sticky=tk.W)
        ttk.Label(main_frame, text="PageUp: 距离10px 间隔30ms | PageDown: 距离37px 间隔30ms").grid(row=3, column=0, columnspan=2, pady=0, sticky=tk.W)
        
        # 距离调整提示
        ttk.Label(main_frame, text="距离调整: 上键增加 | 下键减少").grid(row=4, column=0, columnspan=2, pady=5, sticky=tk.W)
        
        # 控制按钮
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=5, column=0, columnspan=2, pady=10)
        
        self.start_button = ttk.Button(button_frame, text="开启", command=self.start_program)
        self.start_button.pack(side=tk.LEFT, padx=5)
        
        self.stop_button = ttk.Button(button_frame, text="关闭", command=self.stop_program, state=tk.DISABLED)
        self.stop_button.pack(side=tk.LEFT, padx=5)
        
        # 状态显示
        self.status_var = tk.StringVar(value="状态: 未运行")
        ttk.Label(main_frame, textvariable=self.status_var).grid(row=6, column=0, columnspan=2, pady=5)
        
        # 快捷键提示
        ttk.Label(main_frame, text="快捷键: 鼠标滚轮点击 开启/关闭").grid(row=7, column=0, columnspan=2, pady=5)
    
    def start_listeners(self):
        """启动键盘和鼠标监听器"""
        # 鼠标监听器（监听中键和左键）
        self.mouse_listener = mouse.Listener(on_click=self.on_mouse_click)
        self.mouse_listener.start()
        
        # 键盘监听器（监听方向键和PageUp/PageDown）
        self.keyboard_listener = keyboard.Listener(on_press=self.on_key_press)
        self.keyboard_listener.start()
    
    def on_key_press(self, key):
        """处理键盘按键（新增PageUp/PageDown预设参数）"""
        try:
            if key == Key.page_up:
                # PageUp键：设置距离10px，间隔30ms
                self.distance = 10
                self.interval = 0.03  # 30ms
                self.distance_var.set(str(self.distance))
                self.interval_var.set(str(int(self.interval * 1000)))
                print(f"已预设: 下压距离10像素，下压间隔30毫秒")
            
            elif key == Key.page_down:
                # PageDown键：设置距离37px，间隔30ms
                self.distance = 37
                self.interval = 0.03  # 30ms
                self.distance_var.set(str(self.distance))
                self.interval_var.set(str(int(self.interval * 1000)))
                print(f"已预设: 下压距离37像素，下压间隔30毫秒")
            
            elif key == Key.up:
                # 上键：增加下压距离
                self.distance = max(1, self.distance + self.distance_step)
                self.distance_var.set(str(self.distance))
                print(f"下压距离已设置为: {self.distance} 像素")
            
            elif key == Key.down:
                # 下键：减少下压距离
                self.distance = max(1, self.distance - self.distance_step)
                self.distance_var.set(str(self.distance))
                print(f"下压距离已设置为: {self.distance} 像素")
                
        except Exception as e:
            print(f"按键处理错误: {e}")
    
    def on_mouse_click(self, x, y, button, pressed):
        """处理鼠标点击（鼠标中键切换程序状态）"""
        if button == mouse.Button.middle and pressed:
            # 鼠标中键点击，切换程序状态
            if self.running:
                self.stop_program()
            else:
                self.start_program()
            return
        
        # 原有的鼠标左键处理逻辑
        if button == mouse.Button.left:
            self.pressing_fire = pressed
    
    def apply_recoil_control(self):
        """压枪控制线程"""
        while self.running:
            if self.pressing_fire:
                # 读取用户设置
                try:
                    distance = int(self.distance_var.get())
                    interval = float(self.interval_var.get()) / 1000
                    
                    # 应用鼠标下压
                    mouse_event(0, distance)
                    
                    # 等待指定间隔
                    time.sleep(interval)
                except Exception as e:
                    print(f"压枪错误: {e}")
                    time.sleep(0.1)
            else:
                time.sleep(0.01)
    
    def start_program(self):
        """启动程序"""
        if self.running:
            return
            
        # 验证输入
        try:
            distance = int(self.distance_var.get())
            interval = float(self.interval_var.get())
            if distance <= 0 or interval <= 0:
                messagebox.showerror("输入错误", "请输入大于0的数值")
                return
        except ValueError:
            messagebox.showerror("输入错误", "请输入有效的数字")
            return
            
        self.running = True
        self.status_var.set("状态: 运行中")
        self.start_button.config(state=tk.DISABLED)
        self.stop_button.config(state=tk.NORMAL)
        
        # 启动压枪线程
        self.control_thread = threading.Thread(target=self.apply_recoil_control)
        self.control_thread.daemon = True
        self.control_thread.start()
    
    def stop_program(self):
        """停止程序"""
        if not self.running:
            return
            
        self.running = False
        self.status_var.set("状态: 未运行")
        self.start_button.config(state=tk.NORMAL)
        self.stop_button.config(state=tk.DISABLED)
    
    def on_closing(self):
        """处理窗口关闭"""
        self.stop_program()
        self.mouse_listener.stop()
        self.keyboard_listener.stop()
        self.root.destroy()

if __name__ == "__main__":
    root = tk.Tk()
    app = RecoilControlApp(root)
    root.protocol("WM_DELETE_WINDOW", app.on_closing)
    root.mainloop()